// pages/category/index.js
import { request } from "../../request/index.js";
import regeneratorRuntime from "../../lib/runtime/runtime";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 左侧菜单数据
    leftMenuList: [],
    // 右侧商品数据
    rightContent: [],
    // 被点击
    currentIndex: 0,
    scrollTop: 0
  },
  // 接口返回数据
  Cates: [],

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 添加缓存
    const Cates = wx.getStorageSync('cates');
    if(!Cates) {
      this.getCates();
    }else {
      // 过期时间设置
      if(Date.now()-Cates.time>1000*20) {
        this.getCates();
      }else {
        this.Cates = Cates.data;
        let leftMenuList = this.Cates.map(v => v.cat_name)
        let rightContent = this.Cates[0].children;
        this.setData({
          leftMenuList,
          rightContent
        })
      }
    }
    
  },
  // 获取分类数据
  async getCates() {
    // request({
    //   url: "/categories"
    // })
    // .then(res => {
    //   this.Cates = res;
    //   wx.setStorageSync('cates', { time: Date.now(), data: this.Cates });
    //   // 构造左侧数据
    //   let leftMenuList = this.Cates.map(v => v.cat_name)
    //   // 构造右侧数据
    //   let rightContent = this.Cates[0].children;
    //   this.setData({
    //     leftMenuList,
    //     rightContent
    //   })
    // })
    // es7发送异步请求
    const res = await request({url: "/categories"});
    this.Cates = res;
    wx.setStorageSync('cates', { time: Date.now(), data: this.Cates });
    let leftMenuList = this.Cates.map(v => v.cat_name)
    let rightContent = this.Cates[0].children;
    this.setData({
      leftMenuList,
      rightContent
    })
  },
  // 左侧菜单点击事件
  handleItemTap(e) {
    const { index } = e.currentTarget.dataset;
    // 构造右侧数据
    let rightContent = this.Cates[index].children;
    this.setData({
      currentIndex: index,
      rightContent,
      scrollTop: 0
    })
  }
})